using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using GrapeCity.Forguncy.Log;
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Threading.Tasks;
using ImportDataToDataBaseExtensionPlugin.Common;
using ImportDataToDataBaseExtensionPlugin.Helper;

namespace ImportDataToDataBaseExtensionPlugin
{
    [Icon("pack://application:,,,/ImportDataToDataBaseExtensionPlugin;component/Resources/Icon.png")]
    [Designer("ImportDataToDataBaseExtensionPlugin.Designer.ImportDataToDataBaseExtensionPluginServerCommandDesigner, ImportDataToDataBaseExtensionPlugin")]
    public class ImportDataToDataBaseExtensionPluginServerCommand : Command, ICommandExecutableInServerSideAsync
    {
        [Required]
        public int DataBaseType { get; set; }
        
        [DatabaseConnectionSelectorProperty(IncludeBuiltInDatabase = true)]
        [Required]
        public string Connection { get; set; }
        
        [FormulaProperty]
        [Required]
        public object TableName { get; set; }
        
        [FormulaProperty]
        [Required]
        public object FilePath { get; set; }
        
  

        [ResultToProperty]
        [DisplayName("成功导入行数")]
        public string ResultTo { get; set; } = "结果";

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var filePath = (await dataContext.EvaluateFormulaAsync(FilePath)).ToString();
            var dataTable = GetDataFromExcel.ExcelToDatatable(filePath);
            
            
            var dataAccess = dataContext.DataAccess;
            var connectionString = dataAccess.GetConnectionStringByID(Connection);
            
            var tableName = (await dataContext.EvaluateFormulaAsync(TableName)).ToString();

            await ImportDataToDataBaseAsync(connectionString, tableName, dataTable);
            
            dataContext.Parameters[ResultTo] = dataTable.Rows.Count;

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "导入数据到数据库服务端命令";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }

        private async Task ImportDataToDataBaseAsync(string connectionString, string tableName, DataTable dataTable)
        {
            switch (DataBaseType)
            {
                case (int)DataBaseTypeEnum.SqlServer:
                    await InsertDataToDataBaseHelper.InsertDataToSqlServerAsync(connectionString, tableName, dataTable);
                    break;
                case (int)DataBaseTypeEnum.MySql:
                    await InsertDataToDataBaseHelper.InsertDataToMySqlAsync(connectionString, tableName, dataTable);
                    break;
            }
        }
    }
}
